/**
 * 消息列表视图。 
 */
var ChatView = (function() {
    
    function _chatView(chatPanel) {
        var _this = this;        
        this.chatPanel = chatPanel;
        this.chatPanel.chatView = this;
        this.deleted = this.chatPanel.chatGroupEntity['deleted'];
        this.teid = this.chatPanel.teid || this.chatPanel.chatGroupEntity['id'];        
        this.$wrapper = chatPanel.getChatViewPlaceholder();        
        //历史消息翻看逻辑.
        if(chatPanel.mode == 'view'){
            var size = 5;
            var pageSize = size * 2 + 1;
            var middleSeq = parseInt(chatPanel.middleSeq);            
            var msgCount = Math.min(pageSize, 30000);
            var fromSeq = middleSeq + size;
            page.biz.getMsgList(this.teid, fromSeq, msgCount, _this.deleted).done(function(msg){
                var minSeq = middleSeq - size;
                if(minSeq > 1){
                    _this.addLoadMoreBtn(minSeq - 1);
                }
                chatPanel.chatView.addTopic(msg['topics'].reverse());
                if(msg['topics'].length == msgCount){
                    _this.addLoadMoreBtn(fromSeq + pageSize, 'next');
                }
            });
        } else {
            this.$wrapper.on('scroll', function(){
                $('.readerListWrapper').remove();
            });
            //滚动延迟加载 read count.
            this.$wrapper.on('scroll', Function.debounce(function(){
                _this.refreshReadCount();
            }, 500));
        }
    };    
    _chatView.prototype.refreshReadCount = function(){
        var _this = this;        
        (function(){
            page.biz.getReadCount(_this.teid);
        }).defer(200);
        return this;
    };    
    _chatView.prototype.showLoadMore = function(count){
        //加载历史记录.
        var chatGroupEntity = this.chatPanel.chatGroupEntity;
        if(this.chatPanel.mode != 'view' && chatGroupEntity['latestSeq'] > 0 && !ChatGroupPerm.check(chatGroupEntity['perm'], ChatGroupPerm.DESTRUCTMESSAGE)){
            if(chatGroupEntity['latestSeq'] > 30){
                this.addLoadMoreBtn(chatGroupEntity['latestSeq'] - count);
            }            
        }
    };
    
    //----------------------------------------------------------------
    
    _chatView.prototype.addMsg = function(chatMsg, relMsg, msgPosition, relpos){  
        var seq = parseInt(chatMsg.$wrapper.attr('seq') || chatMsg.rawMsg['seq'] || 0);
 
        if(this.$wrapper.find('.chatMsgItem[seq={0}]'.format(seq)).length && parseInt(seq) !== 0){
            return;
        }
          
        if(!relMsg){            
            if(chatMsg.rawMsg && chatMsg.rawMsg['type'] !='next' && seq > 1 && this.getMsgCount() > 0){
                this.addMsg2(chatMsg, seq);
            } else {
                  if(seq === 0){
                        this.$wrapper.append(chatMsg.$wrapper);                  
                  } else {
                        this.addMsg2(chatMsg, seq);
                  }
            } 
        } else {
            var $wrapper = Type.isJQuery(relMsg) ? relMsg : relMsg.$wrapper;
            if(relpos == 'before'){
                $wrapper.before(chatMsg.$wrapper);
            } else {
                $wrapper.after(chatMsg.$wrapper);    
            }
        }
        
        if(Math.abs(seq - this.getLastSeq()) < 5) {
            this.scrollToEnd();
        }
        
        this.refreshReadCount();
        return chatMsg.$wrapper;
    };
    
    _chatView.prototype.addMsg2 = function(chatMsg, seq){        
        var isDone = false;
        var $lastMsg = this.getLastMsg(true);
        
        if($lastMsg.size()){
            do{
                if($lastMsg.attr){
                    var rowSeq = parseInt($lastMsg.attr('seq'));
                    if(seq == rowSeq){
                        return;
                    }
                    if(seq > rowSeq){
                        this.addMsg(chatMsg, $lastMsg, null, 'after');
                        isDone = true;
                        break;
                    }
                }
            } while($lastMsg.prev && ($lastMsg = $lastMsg.prev()) && $lastMsg.size());               
        }   
             
        if(!isDone){
            this.$wrapper.prepend(chatMsg.$wrapper);    
        }
    };
    
    _chatView.prototype.getVisibleRightMsg = function(){
        var children  = this.$wrapper.getVisibleChildren();
        return $.map(children, function($child){
            if($child.hasClass('right')){
                return $child;
            }
        });    
    };
    
    _chatView.prototype.addTopic = function(topic, relMsg, relpos){
        if(Type.isArray(topic)){
            var topics = topic;
            for(var i=0; i<topics.length; i++){
                this.addTopic(topics[i], relMsg, relpos);
            }
            return this;
        }
        var chatMsgConstructor,
            chatMsgObj,
            msgPosition = ujs.util.session.isCurrentUser(topic['user']) ? 'right' : 'left',
            msgType = topic['contentType'];
          
        switch(msgType){
            case MsgType.TEXT :
                chatMsgConstructor = ChatTextMsg;
                break;
            case MsgType.IMAGE :
                chatMsgConstructor = ChatImageMsg;
                break;
            case MsgType.FILE :
                chatMsgConstructor = ChatFileMsg;
                break;
            case MsgType.AUDIO :
                chatMsgConstructor = ChatAudioMsg;
                break;
            case MsgType.VIDEO :
                chatMsgConstructor = ChatVideoMsg;
                break;
            case MsgType.LOCATION :
                chatMsgConstructor = ChatLocationMsg;
                break;
            case MsgType.STICKER :
                chatMsgConstructor = ChatStickerMsg;
                break;
            default:
                chatMsgConstructor = ChatTextMsg;
                break;
        }
        chatMsgObj = new chatMsgConstructor(topic, msgPosition);
        chatMsgObj.render(this, relMsg, msgPosition, relpos);
    };    
    
    _chatView.prototype.scrollToEnd = function(){
        try{
            if(this.chatPanel.topBar.getValues().lockType){
                return false;
            }
        }catch(e){}
        
        var _this = this;
        (function(){
            _this.$wrapper.scrollToEnd();    
        }).defer(0); 
    };
    
    //----------------------------------------------------------------
      
    _chatView.prototype.getLastMsg = function(flag){
        if(flag){
            return this.$wrapper.find('.chatMsgItem, .chatMsgHr').last();
        } else {
            return this.$wrapper.find('.chatMsgItem:last');    
        }
    };
    
    _chatView.prototype.getMsgCount = function(){
        return this.$wrapper.find('.chatMsgItem').size();    
    };
        
    _chatView.prototype.getLastSeq = function(){
        return parseInt(this.$wrapper.find('.chatMsgItem:not(.fail, .sending):last').attr('seq')) || 0;    
    };
    
    _chatView.prototype.getFirstSeq = function(){
        return parseInt(this.$wrapper.find('.chatMsgItem:first').attr('seq')) || 0;    
    };
    
    /**
     * 设置消息已读.
     * @param {Number} seq
     */
    _chatView.prototype.setMsgReaded = function(seq){
        var _this = this;
        this.$wrapper.find('.chatMsgItem').each(function(){
            var $msgItem = $(this),
                msgSeq = parseInt($msgItem.attr('seq'));
            
            var $unread = $msgItem.find('.chatMsgItemContentWrapper');
            if(msgSeq <= seq){                
                $unread.removeClass('unread');
                if(_this.chatPanel.chatGroupEntity.type === 'singlechat'){
                    $unread.addClass('read');
                }
            } else {                                
                if(_this.chatPanel.chatGroupEntity.type === 'singlechat'){
                    $unread.addClass('unread');
                }
            }
        });
    };
    
    _chatView.prototype.addLoadMoreBtn = function(seq, type){
        var loadMoreBar = new ChatLoadMoreMsg({
            seq : seq,
            teid : this.chatPanel.chatGroupEntity['id'],
            type : type
        }); 
        loadMoreBar.chatView = this;
        loadMoreBar.render(this);
        this.loadMoreBar = loadMoreBar;
        return this.loadMoreBar;
    };
    
    _chatView.prototype.clearMsg = function(){
        this.$wrapper.html('');
    };
    
    return _chatView;    
})(); 